<template>
	<u-upload 
	:action="action" 
	:max-size="5 * 1024 * 1024"
	max-count="1"
	:beforeUpload="beforeUpload"
	:custom-btn="true"
	:show-progress="false"
	:form-data="formData"
	:show-upload-list="false"
	:deletable="false"
	@on-success="imgSuccess"
	ref='uploadRef'
	 >
		<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
	 
	 </u-upload>
</template>

<script>
	
	let _this= {}
	export default {
		name:"oss-upload",
		data() {
			return {
				action: 'http://www.example.com/upload',
				formData: {},
				upfileName: ''
				
			}
		},
		
		created() {
			_this = this
		},
		methods:{
			async beforeUpload(index, list){
				
				const {file} = list[0] //设置了最多只能上传一个图片，所以是0
			
				//#ifdef H5
				const fileName = file.name
				//#endif
				//#ifdef APP
				const fileName = file.path
				//#endif
				const ossToken = await _this.$u.api.getoss_token()
				//处理文件名
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				const upfileName = _this.$u.guid(20) + suffix
				
				this.upfileName = upfileName
				_this.action = ossToken.host
				//上传前的参数
				_this.formData={
					'key': upfileName,
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid,
					'success_action_status' : '200',
					'signature': ossToken.signature
				}
			
				return true
			},
			
			async imgSuccess(){
				
				//一旦filelist有了图片后就会被预览区占据，手动移除
				this.$refs.uploadRef.remove(0)
				const res =  await this.$u.api.userAvatar({avatar:this.upfileName})
				
				this.$u.utils.updateUser()
				this.$u.toast('头像更新成功')
			}
			
		}

	}
</script>

<style>

</style>
